package com.wmwu.mybatistest.interceptor;

import com.wmwu.mybatistest.handler.DataCoverageDataAuthHandler;
import com.wmwu.mybatistest.utils.ExecutorPluginUtils;
import org.apache.ibatis.cache.CacheKey;
import org.apache.ibatis.executor.Executor;
import org.apache.ibatis.mapping.BoundSql;
import org.apache.ibatis.mapping.MappedStatement;
import org.apache.ibatis.mapping.SqlCommandType;
import org.apache.ibatis.plugin.Interceptor;
import org.apache.ibatis.plugin.Intercepts;
import org.apache.ibatis.plugin.Invocation;
import org.apache.ibatis.plugin.Plugin;
import org.apache.ibatis.plugin.Signature;
import org.apache.ibatis.session.ResultHandler;
import org.apache.ibatis.session.RowBounds;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.Properties;

/**
 * @author wmwu
 */
@Component
@Intercepts(value = {@Signature(type = Executor.class, method = "query", args = {MappedStatement.class, Object.class, RowBounds.class, ResultHandler.class}),
        @Signature(type = Executor.class, method = "query", args = {MappedStatement.class, Object.class, RowBounds.class, ResultHandler.class, CacheKey.class, BoundSql.class})
})
public class ExecuteStatInterceptor implements Interceptor {

    @Autowired
    DataCoverageDataAuthHandler handler;

    @Override
    public Object intercept(Invocation invocation) throws Throwable {
        SqlCommandType sct = ExecutorPluginUtils.getSqlCommandType(invocation);
        //查询语句为select
        if (SqlCommandType.SELECT == sct) {
            handler.resetSql2Invocation(invocation);
        }
        return invocation.proceed();
    }

    @Override
    public Object plugin(Object o) {
        return Plugin.wrap(o, this);
    }

    @Override
    public void setProperties(Properties properties) {

    }
}
